<template>
  <div>
    <el-row :gutter="10">
      <el-col :span="12">
        <el-card shadow="hover" class="mgb20" style="height:600px;">
          热门的志愿服务
          <el-button type="primary" @click="refreshSupplierData">更新数据</el-button>
          <!--          <div id="supplierChart" class="schart"></div>-->
          <div style="height: 50px"></div>
          <el-table :data="volunteerServices" style="width: 100%">
            <el-table-column prop="serviceName" label="服务名称"></el-table-column>
            <el-table-column prop="serviceType" label="服务类型"></el-table-column>
            <el-table-column prop="serviceValue" label="服务价值"></el-table-column>
            <el-table-column prop="participantCount" label="参与人数"></el-table-column>
          </el-table>
        </el-card>

        <el-card shadow="hover" class="mgb20" style="height:600px;">
          商品库存
          <el-button type="primary" @click="refreshInventoryData">更新数据</el-button>
          <div id="inventoryChart" class="schart"></div>
        </el-card>



      </el-col>

      <el-col :span="12">

        <el-card shadow="hover" class="mgb20" style="height:600px;">
          热门非遗活动
          <el-button type="primary" @click="refreshActiveData">更新数据</el-button>

          <div class="block" style="margin-top: 10px;margin-bottom: 10px">
            <span class="demonstration">选择日期</span>
            <el-date-picker
                v-model="dayvalue"
                align="right"
                type="date"
                placeholder="选择日期"
                :picker-options="pickerOptions">
            </el-date-picker>
          </div>


          <div id="activeChart" class="schart"></div>
        </el-card>

        <el-card shadow="hover" class="mgb20" style="height:600px;">
          热门销售
          <el-button type="primary" @click="refreshSalesData">更新数据</el-button>
          <div id="salesChart" class="schart" style="height: 600px"></div>
        </el-card>



      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import axios from "axios";

export default {
  name: 'dashboard',
  data() {
    return {
      volunteerServices: [
        { serviceName: '陪伴老人', serviceType: '社区服务', serviceValue: '5', participantCount: 20 },
        { serviceName: '环境清理', serviceType: '环保服务', serviceValue: '4', participantCount: 15 },
        { serviceName: '义务教育', serviceType: '教育服务', serviceValue: '5', participantCount: 30 },
        { serviceName: '食物捐赠', serviceType: '慈善服务', serviceValue: '4', participantCount: 25 },
        { serviceName: '公益演出', serviceType: '文化服务', serviceValue: '3', participantCount: 18 },
        { serviceName: '社区义工', serviceType: '社区服务', serviceValue: '4', participantCount: 22 }
        // 更多热门志愿服务数据可以在这里添加
      ],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      dayvalue: '',
      todayText:'2024-4-2',

      salesData:[],
      inventoryData:[],
      activeData:[],
      supplierData: [],

    };
  },

  beforeMount() {
    this.refreshSalesData();
    this.refreshSupplierData();
    this.refreshSupplierData();

  },

  mounted() {
    this.renderSalesChart(); // 渲染销售图表
    this.renderInventoryChart(); // 渲染库存图表
    this.renderActiveChart(); // 渲染热门活动图表
    this.refreshActiveData();
    this.refreshSupplierData();
    this.renderSupplierChart();
    this.renderSupplierChart();
  },
  methods: {

    // 销售数据
    renderSalesChart() {var chartDom = document.getElementById('salesChart');
      var myChart = echarts.init(chartDom);
      var option;

// This example requires ECharts v5.5.0 or later
      option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        series: [
          {
            // name: 'Access From',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['50%', '70%'],
            // adjust the start and end angle
            startAngle: 180,
            endAngle: 360,
            // data: [
            //   { value: 40, name: '老年人专用防滑鞋夏季新款透气' },
            //   { value: 38, name: '正宗山东烟台红富士苹果' },
            //   { value: 32, name: '正宗土鸡农家散养老母鸡现杀' },
            //
            // ]

            data: this.salesData
          }
        ]
      };

      option && myChart.setOption(option);
    },

    // 库存数据
    renderInventoryChart() {
      // 模拟库存数据
      const inventoryData = [
        { name: '老年人专用防滑鞋夏季新款透气', value: 994 },
        { name: '正宗山东烟台红富士苹果', value: 97 },
        { name: '正宗土鸡农家散养老母鸡现杀', value: 998 }
      ];

      // 渲染库存图表
      const chartDom = document.getElementById('inventoryChart');
      const myChart = echarts.init(chartDom);
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: inventoryData.map(item => item.name),
          axisLabel: {
            rotate: 0, // 旋转角度，使标签不重叠
            interval: 0 // 强制显示所有标签
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: inventoryData.map(item => item.value),
          type: 'bar'
        }]
      };
      myChart.setOption(option);
    },

    // 热门活动图表
    renderActiveChart(){
      var chartDom = document.getElementById('activeChart');
      var myChart = echarts.init(chartDom);
      var option;

      option = {
        title: {
          text: this.todayText,
          subtext: '当日热门非遗活动',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',
            radius: '50%',
            data: this.activeData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      option && myChart.setOption(option);
    },

    // 供应商图表
    // 供应商信息图表
    renderSupplierChart() {
      const chartData = this.supplierData.map(item => ({
        name: item.supplier,
        value: item.products
      }));

      const chart = echarts.init(document.getElementById('supplierChart'));

      const option = {
        title: {
          text: ''
        },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: this.supplierData.map(item => item.supplier)
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: chartData,
          type: 'bar'
        }]
      };

      chart.setOption(option);
    },

    // 刷新销售数据
    refreshSalesData(){
      // var response = {
      //   "code": "200",
      //   "msg": "成功",
      //   "data": [
      //     {
      //       "老年人专用防滑鞋夏季新款透气": {
      //         "count": 4,
      //         "inventory": 994
      //       }
      //     },
      //     {
      //       "正宗山东烟台红富士苹果": {
      //         "count": 2,
      //         "inventory": 97
      //       }
      //     },
      //     {
      //       "正宗土鸡农家散养老母鸡现杀": {
      //         "count": 1,
      //         "inventory": 998
      //       }
      //     }
      //   ],
      //   "size": null
      // };
      //
      // this.salesData = response.data.map(item => ({
      //   value: item[Object.keys(item)[0]].count,
      //   name: Object.keys(item)[0]
      // }));
      //
      // // 更新销售图表
      // this.renderSalesChart();
      // this.$message.success("成功更新")

      //真实接口
      axios.post("http://192.168.31.214:1006/getSales").then(response => {
        console.log(response.data)

        // 在这里更新销售数据
        if(response.data.code === '200'){
          this.salesData = response.data.data.map(item => ({
            value: item[Object.keys(item)[0]].count,
            name: Object.keys(item)[0]
          }));
          // 更新销售图表
          this.renderSalesChart();
          this.$message.success("成功更新")
        }
        else {
          this.$message.error("数据有误，稍后再试")
        }

      }).catch(error => {
        this.$message.error("数据有误，稍后再试")
        console.error('Error fetching sales data:', error);
      });



    },

    // 刷新库存数据
    refreshInventoryData(){
      // var response = {
      //   "code": "200",
      //   "msg": "成功",
      //   "data": [
      //     {
      //       "老年人专用防滑鞋夏季新款透气": {
      //         "count": 4,
      //         "inventory": 994
      //       }
      //     },
      //     {
      //       "正宗山东烟台红富士苹果": {
      //         "count": 2,
      //         "inventory": 97
      //       }
      //     },
      //     {
      //       "正宗土鸡农家散养老母鸡现杀": {
      //         "count": 1,
      //         "inventory": 998
      //       }
      //     }
      //   ],
      //   "size": null
      // };
      //
      // this.inventoryData = response.data.map(item => ({
      //   value: item[Object.keys(item)[0]].inventory,
      //   name: Object.keys(item)[0]
      // }));
      //
      // // 更新销售图表
      // this.renderSalesChart();
      // this.$message.success("成功更新")
      //真实接口
      axios.post("http://192.168.31.214:1006/getSales").then(response => {
        // 在这里更新销售数据
        if(response.data.code === '200'){
          this.inventoryData = response.data.data.map(item => ({
            value: item[Object.keys(item)[0]].inventory,
            name: Object.keys(item)[0]
          }));
          // 更新销售图表
          this.renderSalesChart();
          this.$message.success("成功更新")
        }
        else {
          this.$message.error("数据有误，稍后再试")
        }

      }).catch(error => {
        this.$message.error("数据有误，稍后再试")
        console.error('Error fetching sales data:', error);
      });


    },

    // 刷新活动数据
    refreshActiveData(){
      // var response = {
      //   "code": "200",
      //   "msg": "成功",
      //   "data": [
      //     {
      //       "alreadyVolunteer": "1",
      //       "reason": "暂无",
      //       "alreadyJoin": "0",
      //       "joinCount": 10,   // 参与人数
      //       "type": "0",
      //       "auditState": "1",
      //       "auditStateTwo": "0",
      //       "studyState": "0",
      //       "isAutoCancel": "0",
      //       "startTime": "2024-03-31 15:37",
      //       "id": "4fafdf97",
      //       "auditNameTwo": "huangjiehong",
      //       "activeName": "太极拳",
      //       "auditTimeTwo": "暂无",
      //       "address": "北京海淀区",
      //       "docType": "STUDY",
      //       "photo": "http://192.168.31.214:1006//photos/1d62b8c9bd0739d237a08acc.png",
      //       "updateTime": "2024-03-31 14:19:31",
      //       "needVolunteer": "2",
      //       "reasonTwo": "暂无",
      //       "money": "2",
      //       "needJoin": "10",
      //       "auditTime": "2024-03-31 14:17:59",
      //       "createTime": "2024-03-31 14:17:41",
      //       "phone": "1565451565",
      //       "volunteerContent": "活动目的：参与活动并支持其目标。\n志愿者责任：执行指定任务，协助活动顺利进行。\n",
      //       "activeContent": "太极拳是基于阴阳循环、天人合一的中国传统哲学思想和养生观念，以中正圆活为运动特征的传统体育实践。",
      //       "endTime": "2024-03-31 18:16",
      //       "auditName": "admin"
      //     },
      //     {
      //       "alreadyVolunteer": "1",
      //       "reason": "暂无",
      //       "alreadyJoin": "0",
      //       "joinCount": 12,
      //       "type": "0",
      //       "auditState": "1",
      //       "auditStateTwo": "0",
      //       "studyState": "0",
      //       "isAutoCancel": "0",
      //       "startTime": "2024-04-01 14:30",
      //       "id": "dfe3bc26",
      //       "auditNameTwo": "huangjiehong",
      //       "activeName": "宣纸制作",
      //       "auditTimeTwo": "暂无",
      //       "address": "广东哈尔滨",
      //       "docType": "STUDY",
      //       "photo": "http://192.168.31.214:1006//photos/470ce0d80b346c2aef78c33b.png",
      //       "updateTime": "2024-04-01 12:30:52",
      //       "needVolunteer": "1",
      //       "reasonTwo": "暂无",
      //       "money": "1",
      //       "needJoin": "1",
      //       "auditTime": "2024-04-01 12:30:22",
      //       "createTime": "2024-04-01 12:30:15",
      //       "phone": "1",
      //       "volunteerContent": "活动目的：参与活动并支持其目标。\n志愿者责任：执行指定任务，协助活动顺利进行。\n",
      //       "activeContent": "好活",
      //       "endTime": "2024-04-01 15:30",
      //       "auditName": "admin"
      //     },
      //     {
      //       "alreadyVolunteer": "0",
      //       "reason": "暂无",
      //       "alreadyJoin": "1",
      //       "joinCount": 8,
      //       "type": "0",
      //       "auditState": "1",
      //       "auditStateTwo": "0",
      //       "studyState": "6",
      //       "isAutoCancel": "0",
      //       "startTime": "2024-04-01 14:41",
      //       "id": "aa5d8ea4",
      //       "auditNameTwo": "huangjiehong",
      //       "activeName": "金箔制作",
      //       "auditTimeTwo": "暂无",
      //       "address": "1",
      //       "docType": "STUDY",
      //       "photo": "http://192.168.31.214:1006//photos/05dd996d98a373c7ed590767.png",
      //       "updateTime": "2024-04-01 12:08:01",
      //       "needVolunteer": "1",
      //       "reasonTwo": "暂无",
      //       "money": "1",
      //       "needJoin": "1",
      //       "auditTime": "2024-04-01 12:07:38",
      //       "createTime": "2024-04-01 12:07:23",
      //       "phone": "1",
      //       "volunteerContent": "活动目的：参与活动并支持其目标。\n志愿者责任：执行指定任务，协助活动顺利进行。\n",
      //       "activeContent": "1",
      //       "endTime": "2024-04-02 12:07",
      //       "auditName": "admin"
      //     }
      //   ],
      //   "size": null
      // }
      //
      // this.activeData = response.data.map(item => ({
      //   value: item.joinCount,
      //   name: `${item.activeName}-${item.joinCount}人`
      // }));

      let currentDate = ''
      if(this.dayvalue === ''){
        // 获取当前日期
        currentDate = new Date();
      }
      else {
        currentDate = new Date(this.dayvalue);
      }

      // 格式化日期
      const year = currentDate.getFullYear();
      const month = ('0' + (currentDate.getMonth() + 1)).slice(-2); // 月份从0开始，因此要加1
      const day = ('0' + currentDate.getDate()).slice(-2);

      // 获取小时、分钟
      const hours = ('0' + currentDate.getHours()).slice(-2);
      const minutes = ('0' + currentDate.getMinutes()).slice(-2);

      // 格式化日期和时间
      const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;

      console.log(formattedDate); // 输出: 2024-02-23 00:00
      this.todayText = `${year}-${month}-${day}`;

      // 更新活动图表
      this.renderActiveChart();
      // this.$message.success("成功更新");
      //真实接口
      axios.post(`http://192.168.31.214:1006/getHotActive?startTime=${formattedDate}`).then(response => {
        // 在这里更新销售数据
        if(response.data.code === '200'){
          this.activeData = response.data.data.map(item => ({
            value: item.joinCount,
            name: `${item.activeName}-${item.joinCount}人`
          }));
          // 更新销售图表
          this.renderActiveChart();
          this.$message.success("成功更新")
        }
        else {
          this.$message.error("数据有误，稍后再试")
        }

      }).catch(error => {
        this.$message.error("数据有误，稍后再试")
        console.error('Error fetching sales data:', error);
      });
    },

    // 刷新供应商数据
    refreshSupplierData() {
      axios.get("http://192.168.31.214:1006/queryGoods")
          .then(response => {
            if (response.data.code === '200') {
              const supplierIdCount = {};
              const supplierIdsSet = new Set(); // 使用Set来保证唯一性
              response.data.data.forEach(item => {
                const supplierId = item.supplierId;
                supplierIdsSet.add(supplierId); // 使用Set的add方法添加元素
                if (supplierId in supplierIdCount) {
                  supplierIdCount[supplierId]++;
                } else {
                  supplierIdCount[supplierId] = 1;
                }
              });

              const supplierIds = Array.from(supplierIdsSet); // 将Set转换为数组

              // 构建请求数组
              const requests = supplierIds.map(supplierId => {
                return axios.get("http://192.168.31.214:1006/querySupplierDetail", {
                  params: {
                    id: supplierId
                  }
                });
              });

              // 使用Promise.all方法等待所有请求完成
              Promise.all(requests)
                  .then(responses => {
                    // responses是一个数组，包含每个请求的响应
                    this.supplierData = []; // 清空原有供应商数据
                    responses.forEach(response => {
                      const supplierName = response.data.data.name; // 获取供应商名字
                      const supplierId = response.data.data.id; // 获取供应商ID
                      if (supplierId in supplierIdCount) {
                        const productCount = supplierIdCount[supplierId]; // 获取商品数量
                        this.supplierData.push({ supplier: supplierName, products: productCount });
                      }
                    });
                    this.renderSupplierChart(); // 渲染供应商图表
                  })
                  .catch(error => {
                    console.error('Error fetching supplier details:', error);
                  });

              this.$message.success("成功更新");
            } else {
              this.$message.error("数据有误，稍后再试");
            }
          })
          .catch(error => {
            this.$message.error("数据有误，稍后再试");
            console.error('Error fetching sales data:', error);
          });

      // 这里保留您的硬编码的供应商数据和渲染供应商图表的部分
      // this.supplierData = [
      //   { supplier: 'Supplier A', products: 4 },
      //   { supplier: 'Supplier B', products: 3 },
      //   { supplier: 'Supplier C', products: 4 },
      //   { supplier: 'Supplier D', products: 5 },
      //   { supplier: 'Supplier E', products:4  }
      // ];

      // 渲染供应商图表
      this.renderSupplierChart();
    }

  }
};
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}

.grid-content {
  display: flex;
  align-items: center;
  height: 100px;
}

.grid-cont-right {
  flex: 1;
  text-align: center;
  font-size: 14px;
  color: #999;
}

.grid-num {
  font-size: 30px;
  font-weight: bold;
}

.grid-con-icon {
  font-size: 50px;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
  color: #fff;
}

.grid-con-1 .grid-con-icon {
  background: rgb(45, 140, 240);
}

.grid-con-1 .grid-num {
  color: rgb(45, 140, 240);
}

.grid-con-2 .grid-con-icon {
  background: rgb(100, 213, 114);
}

.grid-con-2 .grid-num {
  color: rgb(45, 140, 240);
}

.grid-con-3 .grid-con-icon {
  background: rgb(242, 94, 67);
}

.grid-con-3 .grid-num {
  color: rgb(242, 94, 67);
}

.user-info {
  display: flex;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 2px solid #ccc;
  margin-bottom: 20px;
}

.user-avator {
  width: 120px;
  height: 120px;
  border-radius: 50%;
}

.user-info-cont {
  padding-left: 50px;
  flex: 1;
  font-size: 14px;
  color: #999;
}

.user-info-cont div:first-child {
  font-size: 30px;
  color: #222;
}

.user-info-list {
  font-size: 14px;
  color: #999;
  line-height: 25px;
}

.user-info-list span {
  margin-left: 70px;
}

.mgb20 {
  margin-bottom: 20px;
}

.todo-item {
  font-size: 14px;
}

.todo-item-del {
  text-decoration: line-through;
  color: #999;
}

.schart {
  width: 100%;
  height: 400px;
}
</style>
